import os
import time
import json
from flask import Flask, request, jsonify
from flask import send_from_directory, abort
from flask_cors import CORS

import record

app = Flask(__name__)
CORS(app)  # 添加跨域支持

UPLOAD_FOLDER = 'uploads'
RESULT_FOLDER = 'rets'
app.config['UPLOAD_FOLDER'] = '/'.join(['.', 'app', 'uploads'])
app.config['RESULT_FOLDER'] = '/'.join(['.', 'app', 'rets'])
os.makedirs(app.config['UPLOAD_FOLDER'] , exist_ok=True)
os.makedirs(app.config['RESULT_FOLDER'] , exist_ok=True)

# 添加统计路由
STATS_FILE = './app/stats.json'

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'image0' not in request.files:
        return jsonify({'error': '没有文件被上传'}), 400
    
    image_urls = []
    count=0
    for key in request.files:
        # 
        img = request.files[key]
        if img:
            new_img = 'img'+ str(count) + '.' + img.filename.split('.')[1]      
            img.save('/'.join([app.config['UPLOAD_FOLDER'], new_img]))
        count += 1
    # 返回的 url 应该是经过模型处理之后的新图片的地址
    # 调用模型进行高分辨率重建的API
    image_urls.append(f'http://localhost:5000/{RESULT_FOLDER}/ret.jpg')
    return jsonify({'imageUrl': image_urls,}), 200


@app.route('/superResolution', methods=['POST'])
def get_image():
    index = request.form.get('index')
    return jsonify({'imageUrl': f'http://localhost:5000/{RESULT_FOLDER}/{index}.png',}), 200


@app.route(f'/{RESULT_FOLDER}/<path:filename>')
def serve_uploaded_file(filename):
    return send_from_directory('/'.join(['.', RESULT_FOLDER]), filename)


@app.route('/api/daily-history', methods=['GET'])
def get_daily_history():
    try:
        # 获取最近24小时数据（示例逻辑）
        records = record.read_records() 
        return jsonify({
            'code': 200,
            "data": [{
                "time": item.get('time', ''),
                "caller": item.get('user', '未知用户'),
                "status": item.get('status', 'unknown'),
                "input": item.get('input'),
                "result": item.get('result_url', '')
            } for item in records]
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'error': f'数据获取失败: {str(e)}'
        }), 500


# 新增统计路由
@app.route('/api/stats', methods=['GET', 'POST'])
def handle_stats():
    try:
        if request.method == 'POST':
            return update_stats()
        return get_stats()
    except Exception as e:
        return jsonify({'error': str(e)}), 500

def get_stats():
    if os.path.exists(STATS_FILE):
        with open(STATS_FILE, 'r') as f:
            return jsonify(json.load(f))
    return jsonify({
        "calls": 0,
        "visits": 0,
        "visitors": 0
    })

def update_stats():
    new_data = request.json
    current = json.load(open(STATS_FILE)) if os.path.exists(STATS_FILE) else {}
    updated = {
        "calls": current.get("calls", 0) + new_data.get("calls", 0),
        "visits": current.get("visits", 0) + new_data.get("visit", 0),
        "visitors": current.get("visitors", 0) + new_data.get("newVisitor", 0)
    }
    with open(STATS_FILE, 'w') as f:
        json.dump(updated, f)
    return jsonify(updated)


if __name__ == '__main__':
    app.run(debug=True, threaded=True)
    # 启动分线程
    while(True):
        time.sleep(86400)
        record.start_daily_generation()
    